package plenprojects.chatroomcontrollers;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import plenprojects.exceptions.NotFoundControllerException;
import plenprojects.utils.ImageManager;

@Controller
@RequestMapping("/image")
public class ImageController {
	
	@Autowired
	private ImageManager imageManager;
	
	@RequestMapping(value = "/{username}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)//TODO CAHNGE
	public @ResponseBody byte[] getImage(@PathVariable String username) {
		
		File image = imageManager.findImage(username);
		
		if(image == null) {
			
			throw new NotFoundControllerException();
		}
		
		byte[] bytes = null;
		
		try {
			
			bytes = imageManager.getAllBytes(image);
			
		}
		catch(Exception e) {
			
			throw new RuntimeException(e);
		}
		
		return bytes;
	}
}
